package com.controller;

import com.bean.Cinema;
import com.bean.Films;
import com.bean.Movie;
import com.bean.Seat;
import com.service.CinemaService;
import com.service.FilmsService;
import com.service.MovieService;
import com.service.SeatService;
import com.util.DateUtil;
import com.util.PageAssistant;
import com.vo.CinemaVo;
import com.vo.FilmsVo;
import com.vo.MovieVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("films")
public class FilmsController {
    @Autowired
    private MovieService movieService;
    @Autowired
    private CinemaService cinemaService;
    @Autowired
    private FilmsService filmsService;
    @Autowired
    private SeatService seatService;

    /**
     *
     * @param session
     * @param model
     * @param paCna
     * @return
     */
    @RequestMapping("queryCinema")
    public String films(HttpSession session, Model model, PageAssistant<Cinema> paCna){
        System.out.println(">>>>>>>>> films query ");
        System.out.println("------------------");
        Map<String,Object> map = new HashMap<>();
        map.put("start",paCna.getStart());
        map.put("size",paCna.getSize());
        map.put("state","0");
        paCna.setItems(cinemaService.query(map));
        paCna.setCount(cinemaService.count(map));

        model.addAttribute("paCna",paCna);
        return "page/films/queryCinema";
    }
    @RequestMapping("paipian")
    public String filmsAdd(HttpSession session, Model model, Cinema cinema, Movie movie, String url){
        System.out.println(">>>>>>>>>> films paipian");
        System.out.println(cinema);
        msg(session,model);

        List<Cinema> cinemaList = cinemaService.find(cinema);
        model.addAttribute("cinemas",cinemaList.get(0));

        Map<String,Object> map = new HashMap<>();

        //2年前的当前时间
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR,-2);
        Date startDate = c.getTime();

        //3天后的当前时间
        Calendar c1 = Calendar.getInstance();
        c1.add(Calendar.DATE,3);
        Date stopDate = c1.getTime();

        map.put("startDate",startDate);
        map.put("stopDate",stopDate);
        map.put("state","1");
        List<Movie> movieList = movieService.query(map);
        model.addAttribute("movieList",movieList);
        return "page/films/"+url;
    }




    @RequestMapping("queryAll")
    public String select(HttpSession session, Model model, PageAssistant<Films> paFilms, FilmsVo films, MovieVo movie){
        System.out.println(">>>>>>>>> films queryAll");
        System.out.println(paFilms);
        System.out.println("--------------------------------");
        msg(session,model);
        String start = null;
        String end = null;
        //查询状态正常的影厅
        Map<String,Object> map1 = new HashMap<>();
        map1.put("state","0");
        List<Cinema> cinemaList = cinemaService.query(map1);

        if(films.getStartTime() != null && !films.getStartTime().equals("") && films.getStopTime() != null && !films.getStopTime().equals("")){
            start = films.getStartTime().replaceAll("T", " ") + ":00";
            end = films.getStopTime().replaceAll("T", " ") + ":00";
        }
        map1.clear();
        Map<String,Object> map = new HashMap<>();

        //根据影片名字模糊查询
        map1.put("key",movie.getMovieName());
        List<Movie> movieList = movieService.query(map1);
        if(movieList.size() != 0){
            List<Integer> list = new ArrayList<>();
            for(int i = 0;i<movieList.size();i++){
                list.add(movieList.get(i).getId());
            }
            map.put("ids",list);
        }

        map.put("cinemaId",films.getCinemaId());
        map.put("start",paFilms.getStart());
        map.put("size",paFilms.getSize());
        map.put("startDate",start);
        map.put("stopDate",end);

        paFilms.setCount(filmsService.count(map));
        paFilms.setItems(filmsService.query(map));
        model.addAttribute("date",new Date());

        model.addAttribute("paFilms",paFilms);
        model.addAttribute("cinemaList",cinemaList);
        model.addAttribute("movie",movie);
        model.addAttribute("films",films);

        return "page/films/queryAll";
    }
    @RequestMapping("queryDay")
    public String select1(HttpSession session, Model model, PageAssistant<Films> paFilms){
        System.out.println(">>>>>>>>> films queryDay");
        System.out.println("--------------------------------");

        String startDate = DateUtil.format(new Date(),"yyyy-MM-dd");
        Calendar c = Calendar.getInstance();

        c.add(Calendar.DATE,1);
        String stopDate = DateUtil.format(c.getTime(),"yyyy-MM-dd");
        query(model,startDate,stopDate,paFilms);
        return "page/films/queryDay";
    }
    @RequestMapping("queryWeek")
    public String queryWeek(HttpSession session, Model model, PageAssistant<Films> paFilms, FilmsVo films){
        System.out.println(">>>>>>>>> films queryWeek");
        System.out.println("-------------------------------");

        String startDate = DateUtil.format(new Date(), "yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE,7);
        String stopDate = DateUtil.format(c.getTime(),"yyyy-MM-dd");
        query(model,startDate,stopDate,paFilms);

        return "page/films/queryWeek";
    }
    /**
     * 手动排片
     * @param model
     * @param session
     * @param films
     * @return
     */
    @RequestMapping("manualFilms")
    public String save(Model model,HttpSession session, FilmsVo films,Cinema cinema){
        System.out.println(">>>>>>>>>> films manualFilms");
        System.out.println("start"+films.getStartTime());
        System.out.println("---------------------");
        //开始时间
        long start = 0;
        try {
            Date parse = DateUtil.parse(films.getStartTime().replaceAll("T", " ") + ":00", "yyyy-MM-dd HH:mm:ss");
            //获取开始时间的总毫秒数
            start = parse.getTime();
            String format = DateUtil.format(parse);
            if(format.length()==11){
                format = format+"00:00:00";
            }
            films.setStartTime(format);
        } catch (Exception e) {
            System.out.println("如果报异常了");
        }

        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE,1);
        long date=c.getTime().getTime();

        if(start<date){
            session.setAttribute("msg","播放时间只能排在1天后");
            System.out.println(session.getAttribute("msg"));
            return "redirect:/films/paipian?id="+films.getCinemaId()+"&url=manualFilms";
        }

        //根据影厅编号查询排片表里该影厅的所有记录
        Map<String,Object> map = new HashMap<>();
        map.put("cinemaId",films.getCinemaId());
        List<Films> filmsList = filmsService.query(map);

        map.clear();
        map.put("id",films.getCinemaId());
        List<Cinema> cinemaList = cinemaService.query(map);
        if(cinemaList.get(0).getState() != 0){
            session.setAttribute("msg","该影厅目前处于维护状态,无法放映");
            System.out.println(session.getAttribute("msg"));
            return "redirect:/films/paipian?id="+films.getCinemaId()+"&url=manualFilms";
        }

        //通过选择的电影id拿到该电影的播放时长
        Movie m = new Movie();
        m.setId(Integer.valueOf(films.getMovieId()));
        System.out.println("影片id"+m.getId());
        List<Movie> movieList = movieService.find(m);

        System.out.println("影片名字:"+movieList.get(0).getMovieName());
        System.out.println("该影片的播放时长为:"+movieList.get(0).getDuration());

        try {
            long l = (DateUtil.parse(films.getStartTime()).getTime());
            long l1 = Long.parseLong(movieList.get(0).getDuration() + "")*1000*60;
            //通过开始时间算出影片的结束时间
            String stop = DateUtil.format(new Date(l + l1));
            films.setStopTime(stop);
            System.out.println("转换后的时间:"+stop);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("filmsList长度:"+filmsList.size());
        if(filmsList.size() != 0){
            for (Films f : filmsList ) {
                long startDate = f.getStartTime().getTime();
                long stopDate = f.getStopTime().getTime();
                long spare=0;
                if(f.getSpare() != null){
                    spare = f.getSpare()*60*1000;
                }
                //影片的结束时间
                long stops = 0;
                try {
                    stops =  (DateUtil.parse(films.getStopTime()).getTime())+(Long.parseLong(films.getSpare())*60*1000);
                    System.out.println("影片结束加上间隔后的时间:"+ DateUtil.format(new Date(stops)));
                } catch (Exception e) {
                    System.out.println("如果报异常了");
                }
                if(start>= startDate && start<=stopDate+spare || stops>=startDate && stops<=stopDate){
                    session.setAttribute("msg",f.getCinema().getHall()+"该时间段已有排片信息!");
                    System.out.println(session.getAttribute("msg"));
                    return "redirect:/films/paipian?id="+films.getCinemaId()+"&url=manualFilms";
                }
            }
        }
        films.setState("0");
        int count = filmsService.save(films.parse());
        System.out.println(">>>>>>>>>>>>>>>>>>>");
        System.out.println("films"+films);
        System.out.println(">>>>>>>>>>>>>>>>>>>");
        System.out.println("count:"+count);
        if(count == 1){
            session.setAttribute("msg","排片添加成功");
            //成功之后为座位表添加排片编号
            Seat seat = new Seat();
            seat.setCinemaId(Integer.valueOf(films.getCinemaId()));
       //     System.out.println(seat+",.,.,.,.,><><><><><><选中的影厅的seat");
            //查询选中影厅的seat信息
            List<Seat> seats = seatService.find(seat);
        //    System.out.println(seats+"查询到的seat的信息<><><><<><<>>");
            //查询到刚添加进去的排片的id
            System.out.println(films+",.,.,刚刚添加进去的films");
            List<Films> films1 = filmsService.find(films.parse());
            System.out.println(films1.get(0).getId()+"<><><><><><><><最新id");
            //当座位已经有排片时,直接在后面添加刚刚添加进去的排片信息
            if (seats.get(0).getFilmsId() != null){
                seat.setFilmsId(seats.get(0).getFilmsId()+","+films1.get(0).getId());
                int modify = 0;

                for (int i = 0; i <seats.size() ; i++) {
                    seat.setId(seats.get(i).getId());
                    seatService.modify(seat);

                    modify++;
                }
                System.out.println(modify+"修改座位的个数");
            }else{
                //无排片信息时,直接给选中的影厅添加filmsId字段(添加新增排片编号)
                seat.setFilmsId(films1.get(0).getId()+"");
                int modify = 0;
                for (int i = 0; i <seats.size() ; i++) {
                    seat.setId(seats.get(i).getId());
                    seatService.modify(seat);
                    modify++;
                }
                System.out.println(modify+"修改座位的个数");
            }
            return "redirect:/films/queryAll";
        }

        session.setAttribute("msg","排片添加失败");

        return "redirect:/films/paipian?id="+films.getCinemaId()+"&url=manualFilms";
    }

    /**
     * 自动排片
     * @param films
     * @return
     */
    @RequestMapping("automatic")
    public String  automatic(HttpSession session, Model model, FilmsVo films,Cinema cinema){
        System.out.println(">>>>>>>>> films automatic");

        System.out.println("-------------------------------");
        Date startTime = null;
        Date stopTime = null;
        try {
            startTime = DateUtil.parse(films.getStartTime().replaceAll("T", " ") + ":00", "yyyy-MM-dd HH:mm:ss");
            stopTime = DateUtil.parse(films.getStopTime().replaceAll("T", " ") + ":00", "yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {

        }

        Calendar c1 = Calendar.getInstance();
        c1.add(Calendar.DATE,1);
        if(startTime.getTime()<c1.getTime().getTime()){
            session.setAttribute("msg","只能排在1天之后");
            return "redirect:/films/paipian?id="+films.getCinemaId()+"&url=automaticFilms";
        }

        //查询该电影播放时长
        List<Movie> movies = movieService.find(new Movie(Integer.valueOf(films.getMovieId())));
        int duration = movies.get(0).getDuration();

        //该影片的结束时间
        Calendar c = Calendar.getInstance();
        c.setTime(startTime);
        c.add(Calendar.MINUTE,duration);
        Date stopDate = c.getTime();

        //间隔时间(分钟)
        int spare = 0;
        try {
            spare = Integer.valueOf(films.getSpare());
        } catch (NumberFormatException e) {
            System.out.println("间隔时间只能是数字");
        }
        //根据影厅id查询该影厅在排片表的所有记录
        Map<String, Object> map = new HashMap<>();
        map.put("cinemaId",films.getCinemaId());
        map.put("startDate",startTime);
        map.put("stopDate",stopTime);
        List<Films> filmsList = filmsService.query(map);
        spare = spare*60*1000;
        while(stopDate.getTime()<stopTime.getTime()){
            if (filmsList.size() > 0){
                for (Films f:filmsList) {
                    long std = f.getStartTime().getTime();
                    long stp = f.getStopTime().getTime();
                    long spr = f.getSpare()*60*1000;
                    if(startTime.getTime()>=std && startTime.getTime()<stp+spr || stopDate.getTime()+spare>std && stopDate.getTime()+spare<=stp){
                        startTime = new Date(stp+spr);
                        stopDate = new Date(startTime.getTime()+duration*60*1000);
                    }
                }
            }
            films.setState("0");
            String s = DateUtil.format(startTime);
            if(s.length()==11){
                s = s+"00:00:00";
            }
            films.setStartTime(s);
            films.setStopTime(DateUtil.format(stopDate));

            if(stopDate.getTime()<stopTime.getTime()) {
                int save = filmsService.save(films.parse());
                Seat seat = new Seat();
                seat.setCinemaId(Integer.valueOf(films.getCinemaId()));
            //    System.out.println(seat + ",.,.,.,.,><><><><><><选中的影厅的seat");
                //查询选中影厅的seat信息
                List<Seat> seats = seatService.find(seat);
            //    System.out.println(seats + "查询到的seat的信息<><><><<><<>>");
                //查询到刚添加进去的排片的id
                System.out.println(films + ",.,.,刚刚添加进去的films");
                List<Films> films1 = filmsService.find(films.parse());
                System.out.println(films1.get(0).getId() + "<><><><><><><><最新id");
                //当座位已经有排片时,直接在后面添加刚刚添加进去的排片信息
                if (seats.get(0).getFilmsId() != null) {
                    seat.setFilmsId(seats.get(0).getFilmsId() + "," + films1.get(0).getId());
                    int modify = 0;

                    for (int i = 0; i < seats.size(); i++) {
                        seat.setId(seats.get(i).getId());
                        seatService.modify(seat);

                        modify++;
                    }
                    System.out.println(modify + "修改座位的个数");
                } else {
                    //无排片信息时,直接给选中的影厅添加filmsId字段(添加新增排片编号)
                    seat.setFilmsId(films1.get(0).getId() + "");
                    int modify = 0;
                    for (int i = 0; i < seats.size(); i++) {

                        seat.setId(seats.get(i).getId());

                        seatService.modify(seat);
                        modify++;
                    }
                    System.out.println(modify + "修改座位的个数");

                }
            }
            startTime = new Date(stopDate.getTime()+spare);
            stopDate = new Date(startTime.getTime()+duration*60*1000);

    }
        return "redirect:/films/queryAll";
    }



    @RequestMapping("updateQuery")
    public String update(HttpSession session, Model model, PageAssistant<Films> paFilms,FilmsVo films,MovieVo movie){
        System.out.println(">>>>>> films updateQuery");
        System.out.println("------------");

        String start = null;
        String end = null;
        //查询状态正常的影厅
        Map<String ,Object> map = new HashMap<>();
        map.put("state","0");
        List<Cinema> cinemaList = cinemaService.query(map);

        if(films.getStartTime() != null && !films.getStartTime().equals("") && films.getStopTime() != null && !films.getStopTime().equals("")){
            start = films.getStartTime().replaceAll("T", " ") + ":00";
            end = films.getStopTime().replaceAll("T", " ") + ":00";
        }
        map.clear();

        //根据影片名字模糊查询
        map.put("key",movie.getMovieName());
        List<Movie> movieList = movieService.query(map);
        if(movieList.size() != 0){
            List<Integer> list = new ArrayList<>();
            for(int i = 0;i<movieList.size();i++){
                list.add(movieList.get(i).getId());
            }
            map.put("ids",list);
        }

        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE,3);

        map.put("cinemaId",films.getCinemaId());
        map.put("start",paFilms.getStart());
        map.put("size",paFilms.getSize());
        map.put("startDate",start);
        map.put("stopDate",end);
        map.put("end",c.getTime());

        paFilms.setCount(filmsService.count(map));
        paFilms.setItems(filmsService.query(map));

        model.addAttribute("date",new Date());
        model.addAttribute("paFilms",paFilms);
        model.addAttribute("cinemaList",cinemaList);
        model.addAttribute("movie",movie);
        model.addAttribute("films",films);

        return "page/films/updateFilms";
    }
    @RequestMapping("unique")
    public String unique(HttpSession session,Model model, Films films, CinemaVo cinema){
        System.out.println(">>>>> films unique");
        System.out.println(films);
        msg(session,model);
        Map<String,Object> map = new HashMap<>();
        map.put("state","0");
        List<Cinema> cinemaList = cinemaService.query(map);

        //2年前的当前时间
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR,-2);
        Date startDate = c.getTime();

        //3天后的当前时间
        Calendar c1 = Calendar.getInstance();
        c1.add(Calendar.DATE,3);
        Date stopDate = c1.getTime();
        map.clear();
        map.put("startDate",startDate);
        map.put("stopDate",stopDate);
        map.put("state","1");

        List<Movie> movieList = movieService.query(map);

        //根据传过来的id查询到的排片信息
        Films filmsUnique = filmsService.find(films).get(0);

        model.addAttribute("cinemaList",cinemaList);
        model.addAttribute("movieList",movieList);
        model.addAttribute("filmsUnique",filmsUnique);

        return "page/films/unique";
    }
    @RequestMapping("modify")
    public String modify(HttpSession session,Model model,FilmsVo films){
        System.out.println(">>>>>> films modify");
        System.out.println(films);
        System.out.println("---------------------");
        Map<String,Object> map = new HashMap<>();
        String startDate = null;
        String stopDate = null;
        long startTime= 0;
        long stopTime = 0;
        long spare = Integer.valueOf(films.getSpare())*60*1000;

        //根据影片id拿到该影片的播放时长
        List<Movie> movies = movieService.find(new Movie(Integer.valueOf(films.getMovieId())));
        int duration = movies.get(0).getDuration();
        System.out.println("要修改的影片的播放时长:"+duration);
        if(films.getStartTime() != null && !films.getStartTime().equals("")){
            startDate = films.getStartTime().replaceAll("T"," ")+":00";
            try {
                startTime = DateUtil.parse(startDate).getTime();
                stopTime = startTime+duration*60*1000;
                stopDate = DateUtil.format(new Date(stopTime));
            } catch (Exception e) {
                System.out.println("如果报异常了");
            }
        }

        //获取2天后的时间
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE,2);
        //时
        c.set(Calendar.HOUR_OF_DAY, 0);
        // 分
        c.set(Calendar.MINUTE, 0);
        // 秒
        c.set(Calendar.SECOND, 0);
        // 毫秒
        c.set(Calendar.MILLISECOND, 0);

        if(startTime<c.getTimeInMillis()){
            session.setAttribute("msg","排片开始时间只能在一天后");
            return "redirect:/films/unique?id="+films.getId();
        }


        map.clear();
        //根据变更的影厅判断
        map.put("cinemaId",films.getCinemaId());
        map.put("end",new Date());
        List<Films> cinList = filmsService.query(map);
        System.out.println("要修改的影厅是否有排片"+cinList.size());
        //如果该影厅有排片信息,判断
        if(cinList.size()>0){
            for(int i = 0;i<cinList.size();i++){
                long start = cinList.get(i).getStartTime().getTime();
                long end = cinList.get(i).getStopTime().getTime();
                long jg = cinList.get(i).getSpare()*60*1000;
                if(startTime>=start && startTime<end+jg || stopTime+spare>=start && stopTime+spare<end+jg){
                    session.setAttribute("msg","该时间段已有排片信息");
                    return "redirect:/films/unique?id="+films.getId();
                }
            }
        }
        films.setStartTime(startDate);
        films.setStopTime(stopDate);
        System.out.println("要修改的信息"+films);
        int modify = filmsService.modify(films.parse());
        if(modify == 1){
           session.setAttribute("msg","修改成功");

        }else{
            session.setAttribute("msg","修改失败");
        }

        return "redirect:/films/unique?id="+films.getId();
    }
    @RequestMapping("delete")
    public String delete(HttpSession session,Films films){
        System.out.println(">>>>>>>> films delete");
        System.out.println(films);
        System.out.println("------------------");

        int remove = filmsService.remove(films);
        if(remove == 1){
            session.setAttribute("msg","删除成功!");
            return "redirect:/films/updateQuery";
        }

        session.setAttribute("msg","删除失败!");

        return "redirect:/films/unique?id="+films.getId();
    }

    private void query(Model model, String startDate, String stopDate, PageAssistant<Films> paFilms){
        Map<String,Object> map = new HashMap<>();

        map.put("start",paFilms.getStart());
        map.put("size",paFilms.getSize());
        map.put("startDate",startDate);
        map.put("stopDate",stopDate);

        paFilms.setCount(filmsService.count(map));
        paFilms.setItems(filmsService.query(map));
        model.addAttribute("date",new Date());
        model.addAttribute("paFilms",paFilms);
    }

    private void msg(HttpSession session,Model model){
        if(session.getAttribute("msg")!= null){
            model.addAttribute("msg",session.getAttribute("msg"));
            session.removeAttribute("msg");
        }
    }

}
